<?php
/* config */
$user_db = "users.txt";

$_T = time();

require_once ("Comet.php");

$user = $_GET['user'];
$msg = $_GET['msg'];
$msgtype = $_GET['msgtype'];

if(get_magic_quotes_gpc() == 1) {
	$user = stripslashes($user);
	$msg = stripslashes($msg);
}

$comet = new Comet("192.168.1.110", 6000);

if($msgtype == 'leave') {
	delUser($user_db, $user);
	$users = getUsers($user_db);
	foreach($users as $u) {
		if(empty($u)) continue;
		$data = toJson(array(
			'time' => date("H:i:s"),
			'from' => 'SYSTEM',
			'to' => $u,
			'msg' => '<font color="red"><b>user [' . $user . '] leave.</b>'
		));
		$comet->send($u, $data);
	}
	$comet->delUser($user);
	exit();
}

// add user
if(!hasUser($user_db, $user)) {
	$users = getUsers($user_db);
	foreach($users as $u) {
		if(empty($u)) continue;
		$data = toJson(array(
			'time' => date("H:i:s"),
			'from' => 'SYSTEM',
			'to' => $u,
			'msg' => '<font color="green"><b>user [' . $user . '] enter.</b>'
		));
		$comet->send($u, $data);
	}
	addUser($user_db, $user);
}

if($msg != '') {	// deliver msg to every user
	$users = getUsers($user_db);
	foreach($users as $u) {
		if(empty($u)) continue;
		$data = toJson(array(
			'time' => date("H:i:s"),
			'from' => $user,
			'to' => $u,
			'msg' => $msg
		));
		// echo "/* $data */";
		$comet->send($u, $data);
	}
}

// wait for new msg come
echo $comet->recv($user);

function getUsers($user_db) {
	$content = file_get_contents($user_db);
	$users = explode("\n", $content);
	return $users;	
}

function hasUser($user_db, $user) {
	return in_array($user, getUsers($user_db));
}

function addUser($user_db, $user) {
	$users = getUsers($user_db);
	if(!in_array($user, $users)) {	// not exists, insert into db
		$fp = fopen($user_db, "a+");
		if(!$fp) die("open db error, check permit plz");
		fputs($fp, $user . "\n");
		fclose($fp);
	}
}

function delUser($user_db, $user) {
	$users = getUsers($user_db);
	$newUsers = array();
	foreach($users as $u) {
		if($u != $user)
			array_push($newUsers, $u);		
	}
	$newContent = join("\n", $newUsers);
	echo "/* $newContent */";
	$fp = fopen($user_db, "w");
	fputs($fp, $newContent);
	fclose($fp);
}

function toJson($arr) {
	$tmp = array();
	foreach($arr as $key => $val) {
		array_push($tmp, $key . ': "' . escape($val) . '"');
	}
	return '{' . join($tmp, ', ') . '}';
}

function escape($str) {
	return preg_replace('/(["\'\\\\])/', '\\\\$1', $str);	
}

$_T = time() - $_T;
echo "/* execute cost: $_T ms */";

?>
